package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.PageRes;
import com.example.demo.bean.SysJob;
import com.example.demo.constant.Constants;
import com.example.demo.constant.ScheduleConstants;
import com.example.demo.dto.task.SysJobPageReqVO;
import com.example.demo.exception.OtherException;
import com.example.demo.exception.TaskException;
import com.example.demo.mapper.SysJobMapper;
import com.example.demo.service.ISysJobService;
import com.example.demo.utils.CronUtils;
import com.example.demo.utils.ScheduleUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private SysJobMapper sysJobMapper;

    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> jobList = sysJobMapper.selectList(null);
        log.info("已加载定时任务总数：{}", jobList);
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Override
    public PageRes<SysJob> list(SysJobPageReqVO sysJobPageReqVO) {
        return sysJobMapper.selectPage(sysJobPageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob sysJob) throws SchedulerException {
        validSysJobExist(sysJob.getJobId());
        int rows = 0;
        if (ScheduleConstants.Status.NORMAL.value().equals(sysJob.getStatus())) {
            rows = resumeJob(sysJob);
        }
        if (ScheduleConstants.Status.PAUSE.value().equals(sysJob.getStatus())) {
            rows = pauseJob(sysJob);
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob sysJob) throws SchedulerException {
        validSysJobStatusValid(sysJob.getJobId(), sysJob.getStatus());
        int rows = sysJobMapper.updateById(sysJob);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(sysJob.getJobId(), sysJob.getJobGroup()));
        }
        return rows;
    }

    @Override
    public int pauseJob(SysJob sysJob) throws SchedulerException {
        validSysJobStatusValid(sysJob.getJobId(), sysJob.getStatus());
        int rows = sysJobMapper.updateById(sysJob);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(sysJob.getJobId(), sysJob.getJobGroup()));
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(SysJob sysJob) throws SchedulerException, TaskException {
        validSysJobCronExp(sysJob);
        sysJob.setStatus(ScheduleConstants.Status.PAUSE.value());
        int rows = sysJobMapper.insert(sysJob);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, sysJob);
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(SysJob sysJob) throws SchedulerException, TaskException {
        validSysJobExist(sysJob.getJobId());
        validSysJobCronExp(sysJob);
        SysJob preSysJob = getSysJob(sysJob);
        int rows = sysJobMapper.updateById(sysJob);
        if (rows > 0) {
            updateSchedulerJob(sysJob, preSysJob.getJobGroup());
        }
        return rows;
    }

    @Override
    public SysJob getSysJob(SysJob sysJob) {
        validSysJobExist(sysJob.getJobId());
        return sysJobMapper.selectById(sysJob.getJobId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSysJob(Long[] jobIds) throws SchedulerException{
        int deleteCount = 0;
        for (Long jobId : jobIds){
            SysJob job = sysJobMapper.selectById(jobId);
            int rows = sysJobMapper.deleteById(jobId);
            if( rows > 0){
                scheduler.deleteJob(ScheduleUtils.getJobKey(jobId,job.getJobGroup()));
            }
            deleteCount += rows;
        }
        return deleteCount;
    }

    @Override
    public boolean run(SysJob sysJob) throws SchedulerException {
        validSysJobExist(sysJob.getJobId());
        boolean result = false;
        Long jobId = sysJob.getJobId();
        String jobGroup = sysJob.getJobGroup();
        SysJob properties = sysJobMapper.selectById(jobId);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES,properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if(scheduler.checkExists(jobKey)){
            result = true;
            scheduler.triggerJob(jobKey,dataMap);
        }
        return result;
    }

    private void validSysJobExist(Long jobId) {
        SysJob exist = sysJobMapper.selectById(jobId);
        if (exist == null) {
            throw new OtherException("任务不存在");
        }
    }

    private void validSysJobStatusValid(Long jobId, Integer changeStatus) {
        SysJob exist = sysJobMapper.selectById(jobId);
        if (ScheduleConstants.Status.NORMAL.value().equals(changeStatus) && exist.getStatus() != 0) {
            throw new OtherException("任务已启动");
        }
        if (ScheduleConstants.Status.PAUSE.value().equals(changeStatus) && exist.getStatus() != 1) {
            throw new OtherException("任务已暂停");
        }
    }

    private void validSysJobCronExp(SysJob sysJob) {
        if (!CronUtils.isValid(sysJob.getCronExp())) {
            throw new OtherException("Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(sysJob.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            throw new OtherException("目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(sysJob.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            throw new OtherException("目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(sysJob.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            throw new OtherException("目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(sysJob.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            throw new OtherException("目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(sysJob.getInvokeTarget())) {
            throw new OtherException("目标字符串不在白名单内");
        }
    }

    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        JobKey jobKey = ScheduleUtils.getJobKey(job.getJobId(), jobGroup);
        if(scheduler.checkExists(jobKey)){
            // 防止创建时存在数据问题 现移除 再创建
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler,job);
    }
}
